package dao

import (
	"strconv"
	"time"
)

// 这是 RegLimit 的全局公开dao对象
var RegLimitDao = regLimitDao{}

// 注意:这是 RegLimit 的私有dao对象
type regLimitDao struct {
	Obj       RegLimit
	Insert    func(arg RegLimit) int64                          //插入一条记录
	Update    func(arg RegLimit) int64                          //更新一条记录
	Delete    func(createAt time.Time) int64                    `arg:"created_at"` //删除一条记录
	Select    func(arg RegLimit) RegLimit                       //获取一条记录
	GetIp     func(ip string, startTime, endTime time.Time) int `arg:"ip,start_time,end_time"`
	GetOption func(args []string) []Option
}

func (it *regLimitDao) NewRegLimit() *regLimitDao {
	// select option_name,option_value from option where option_name in (REAL_IP_FIELD,HOUR_REG_NUM,DAILY_REG_NUM)
	array := it.GetOption([]string{"REAL_IP_FIELD", "HOUR_REG_NUM", "DAILY_REG_NUM"})
	for _, item := range array {
		switch item.OptionName {
		case "REAL_IP_FIELD":
			it.Obj.RealIpField = item.OptionValue
		case "HOUR_REG_NUM":
			it.Obj.HourRegNum, _ = strconv.Atoi(item.OptionValue)
		case "DAILY_REG_NUM":
			it.Obj.DailyRegNum, _ = strconv.Atoi(item.OptionValue)
		}
	}
	return it
}

func (it *regLimitDao) IPisAllowed(ip string) (allowHour, allowDaily bool) {
	now := time.Now()
	if it.Obj.HourRegNum > 0 {
		hourBefore := now.Add(-1 * time.Hour)
		if count := it.GetIp(ip, hourBefore, now); count >= it.Obj.HourRegNum {
			return false, true
		}
	}
	dayBefore := now.Add(-24 * time.Hour)
	if it.Obj.DailyRegNum > 0 {
		if count := it.GetIp(ip, dayBefore, now); count >= it.Obj.DailyRegNum {
			return true, false
		}
	}
	it.Delete(dayBefore)
	return true, true
}
